package com.xhb.ui.tools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.FrameGrabber.Exception;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BaiduUtil {
	
	 public static final String API_KEY = "AkWhTgdtECzV8HU0E5Aj7vMc";
	 public static final String SECRET_KEY = "06GwBkTZQXa3hcdRFc3R0691drXi5d1I";

	 static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

		/**
		 * 百度人脸
		 * 
		 * @param base64
		 * @return
		 */
		public static boolean face(String[] base64) {
			try {
				MediaType mediaType = MediaType.parse("application/json");
				JSONArray jsonArray = new JSONArray();
				JSONObject param0 = new JSONObject();
				param0.put("image", base64[0]);
				param0.put("image_type", "BASE64");

				JSONObject param1 = new JSONObject();
				param1.put("image", base64[1]);
				param1.put("liveness_control", "LOW");
				param1.put("image_type", "BASE64");

				jsonArray.add(param0);
				jsonArray.add(param1);

				RequestBody body = RequestBody.create(mediaType, jsonArray.toString());
				Request request = new Request.Builder()
						.url("https://aip.baidubce.com/rest/2.0/face/v3/match?access_token=" + getAccessToken())
						.method("POST", body).addHeader("Content-Type", "application/json").build();
				Response response = HTTP_CLIENT.newCall(request).execute();

				String responseBody = response.body().string();

				System.out.println(responseBody);

				JSONObject jsonObject = JSONObject.parseObject(responseBody);
				
				String msg=jsonObject.getString("error_msg");
				if (!org.apache.commons.lang3.StringUtils.equals("SUCCESS", msg)) {
					throw new RuntimeException(jsonObject.getString("error_msg"));
				}
				JSONObject result = jsonObject.getJSONObject("result");
				Long score = result.getLong("score");
				if (score > 85) {
					return true;
				}

				return false;
			} catch (java.lang.Exception e) {
				LogFormat.info(e.getMessage());
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
		}
	
		
		/**
		 * 活体检测
		 * @throws IOException 
		 */
		public static boolean faceliving(String[] base64) {
			try {

				JSONArray jsonArray = new JSONArray();
				JSONObject param0 = new JSONObject();
				param0.put("image", base64[0]);
				param0.put("image_type", "BASE64");

				JSONObject param1 = new JSONObject();
				param1.put("image", base64[1]);
				param1.put("image_type", "BASE64");

				JSONObject param2 = new JSONObject();
				param2.put("image", base64[1]);
				param2.put("image_type", "BASE64");

				jsonArray.add(param0);
				jsonArray.add(param1);
				jsonArray.add(param2);

				MediaType mediaType = MediaType.parse("application/json");
				RequestBody body = RequestBody.create(mediaType, jsonArray.toString());
				Request request = new Request.Builder()
						.url("https://aip.baidubce.com/rest/2.0/face/v3/faceverify?access_token=" + getAccessToken())
						.method("POST", body).addHeader("Content-Type", "application/json").build();
				Response response = HTTP_CLIENT.newCall(request).execute();

				String responseBody = response.body().string();

				System.out.println(responseBody);

				JSONObject jsonObject = JSONObject.parseObject(responseBody);

				String msg = jsonObject.getString("error_msg");
				if (!org.apache.commons.lang3.StringUtils.equals("SUCCESS", msg)) {
					throw new RuntimeException(jsonObject.getString("error_msg"));
				}
				JSONObject result = jsonObject.getJSONObject("result");
				Double face_liveness = result.getDouble("face_liveness");
				if (face_liveness > 0.95) {
					return true;
				}
				return false;
			} catch (java.lang.Exception e) {
				LogFormat.info(e.getMessage());
				e.printStackTrace();
				throw new RuntimeException(e.getMessage());
			}
		}
    
    
    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return JSONObject.parseObject(response.body().string()).getString("access_token");
    }
    
    
	public static void checkImg(String path) {
		File parentDir = new File(path + "\\n");
		// 检查视频是否全部生成 如果已经全部生成 就不走生成逻辑
		for (File v : parentDir.listFiles()) {
			// 视频目录
			// 用户头像
			File headPicFile = new File(path + "/head.jpg");
			// 头像不存在
			if (!headPicFile.exists()) {
				return;
			}
			// 人脸识别
			String base64_0 = PicUtil.convertToBase64(headPicFile.getPath());
			String base64_1 = PicUtil.convertToBase64(v.getPath());
			try {
				boolean face = face(new String[] { base64_0, base64_1 });
				if (!face) {
					v.renameTo(new File(v.getPath() + "_error.png"));
					continue;
				}
			} catch (java.lang.Exception e) {
				v.renameTo(new File(v.getPath() + "_error"+e.getMessage()+".png"));
				continue;
			}
		}
	}
    
	public static void check(String path) {
		File parentDir = new File(path);
		
		File [] files=parentDir.listFiles();
		if(path.contains("-")) {
			files=new File[] {new File(path)};
		}
		
		// 检查视频是否全部生成 如果已经全部生成 就不走生成逻辑
		for (File dir : files) {
			// 视频目录
			String videoDir = dir.getPath() + "/video";
			// 用户头像
			File headPicFile = new File(dir.getPath() + "/head.jpg");
			// 头像不存在
			if (!headPicFile.exists()) {
				continue;
			}
			// 开始检测生成视频是否过关
			File videoDirFile = new File(videoDir);

			for (File v : videoDirFile.listFiles()) {
				File vf = new File(v.getPath() + "/result.mp4");
				// 生成3张照片
				try {
					cutVideotoImg(vf.getPath());
				} catch (IOException e) {
					FileUtil.appendUtf8String(v.getPath() + "/result" + e.getMessage() + ".mp4", videoDir+"/videocheck.conf");
					continue;
				}
				// 人脸识别
//				String base64_0 = PicUtil.convertToBase64(headPicFile.getPath());
//				String base64_1 = PicUtil.convertToBase64(vf.getPath() + "_1.png");
//				try {
//					boolean face = face(new String[] { base64_0, base64_1 });
//					if (!face) {
//						FileUtil.appendUtf8String(v.getPath() + "人脸失败", videoDir+"/videocheck.conf");
//						continue;
//					}
//				} catch (java.lang.Exception e) {
//					FileUtil.appendUtf8String(v.getPath() + "人脸失败" + e.getMessage(), videoDir+"/videocheck.conf");
//					continue;
//				}
//				try {
//					// 活体检测
//					String base64_2 = PicUtil.convertToBase64(vf.getPath() + "_2.png");
//					String base64_3 = PicUtil.convertToBase64(vf.getPath() + "_3.png");
//					boolean faceliving = faceliving(new String[] { base64_1, base64_2, base64_3 });
//					if (!faceliving) {
//						FileUtil.appendUtf8String(v.getPath() + "活体检测失败", videoDir+"/videocheck.conf");
//						continue;
//					}
//				} catch (java.lang.Exception e) {
//					FileUtil.appendUtf8String(v.getPath() + "活体检测失败" + e.getMessage(), videoDir+"/videocheck.conf");
//					continue;
//				}
			}
		}
	}
    
    
	public static void cutVideotoImg(String vodeoPath) throws IOException {

		File file = new File(vodeoPath);
		if (!file.exists()) {
			return;
		}
		
		if(new File(vodeoPath + "_1.png").exists() && new File(vodeoPath + "_2.png").exists() && new File(vodeoPath + "_3.png").exists()) {
			return;
		}

		Integer start = RandomUtil.randomInt(1, 7);

		FFmpegFrameGrabber ff = FFmpegFrameGrabber.createDefault(vodeoPath);
		ff.start();
		// 获取第1000000微秒在当前视频的帧数
		// 单位 微妙 1秒 = 1000000微秒
		ff.setAudioTimestamp(1000000 * start);
		Java2DFrameConverter converter = new Java2DFrameConverter();
		BufferedImage image = converter.convert(ff.grabImage());
		// 本地图片保存地址
		ImageIO.write(image, "png", new File(vodeoPath + "_1.png"));

		ff = FFmpegFrameGrabber.createDefault(vodeoPath);
		ff.start();
		// 获取第1000000微秒在当前视频的帧数
		// 单位 微妙 1秒 = 1000000微秒
		ff.setAudioTimestamp(1000000 * start + 1);
		converter = new Java2DFrameConverter();
		image = converter.convert(ff.grabImage());
		// 本地图片保存地址
		ImageIO.write(image, "png", new File(vodeoPath + "_2.png"));

		ff = FFmpegFrameGrabber.createDefault(vodeoPath);
		ff.start();
		// 获取第1000000微秒在当前视频的帧数
		// 单位 微妙 1秒 = 1000000微秒
		ff.setAudioTimestamp(1000000 * start + 2);
		converter = new Java2DFrameConverter();
		image = converter.convert(ff.grabImage());
		// 本地图片保存地址
		ImageIO.write(image, "png", new File(vodeoPath + "_3.png"));
	}
    
	public static void main(String[] args) throws IOException {
		FFmpegFrameGrabber ff = FFmpegFrameGrabber
				.createDefault("C:\\zgymw\\江西学员名单\\沈华聪-土建施工员-360281199705173617\\result (13).mp4");
		ff.start();
		// 获取第1000000微秒在当前视频的帧数
		// 单位 微妙 1秒 = 1000000微秒
		ff.setAudioTimestamp(1000000 * 3);

		Java2DFrameConverter converter = new Java2DFrameConverter();

		BufferedImage image = converter.convert(ff.grabImage());

		// 本地图片保存地址
		ImageIO.write(image, "png", new File("C:\\zgymw\\江西学员名单\\沈华聪-土建施工员-360281199705173617\\s\\new3.png"));

		BaiduUtil.faceliving(
				new String[] { PicUtil.convertToBase64("C:\\zgymw\\江西学员名单\\沈华聪-土建施工员-360281199705173617\\s\\new.png"),
						PicUtil.convertToBase64("C:\\zgymw\\江西学员名单\\沈华聪-土建施工员-360281199705173617\\s\\new2.png"),
						PicUtil.convertToBase64("C:\\zgymw\\江西学员名单\\沈华聪-土建施工员-360281199705173617\\s\\new3.png") });
	}
}
